package com.rightsidetech.http.controller.admin.agent;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.ModifyName;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.ModifyLog;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.entity.MallAgentCommodity;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.system.dtos.request.UpdateOpenStatus;
import com.rightsidetech.system.dtos.request.agent.AddAgentInfoReq;
import com.rightsidetech.system.dtos.request.agent.AgentInfoReq;
import com.rightsidetech.system.dtos.request.agent.AreaAgentListReq;
import com.rightsidetech.system.dtos.request.agent.UpdateAgentInfoReq;
import com.rightsidetech.system.dtos.request.store.ActAreaAgentStoreReq;
import com.rightsidetech.system.dtos.response.agent.AgentInfoResp;
import com.rightsidetech.system.dtos.response.agent.AgentListResp;
import com.rightsidetech.system.dtos.response.agent.AgentSearchResp;
import com.rightsidetech.system.dtos.response.agent.AreaAgentListResp;
import com.rightsidetech.system.dtos.response.store.ActAgentResp;
import com.rightsidetech.system.dtos.response.store.ActAreaAgentStoreResp;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.service.AgentInfoService;
import com.rightsidetech.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package: com.rightsidetech.http.controller.admin.agent
 * @ClassName: AgentInfoController
 * @Author: yinj
 * @CreateTime: 2021/10/26 11:34
 * @Description: 代理商信息相关api
 */
@Slf4j
@RestController
@RequestMapping("/admin/sys_agent")
@ShenyuSpringMvcClient(path = "/admin/sys_agent/**")
@Api(tags = "代理商信息相关api")
public class AgentInfoController extends BaseController {

    @Resource
    private AgentInfoService agentInfoService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private SysUserService sysUserService;

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/page")
    @ApiOperation("分页")
    public ResponseData<PageInfo<AgentInfoResp>> page(AgentInfoReq request){
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginId = Long.parseLong(getAttribute());
        SysUserLoginInfo loginInfo = sysUserService.selectUserById(loginId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        if (loginInfo.getSysCompanyAreaId() != 0){
            request.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        return agentInfoService.page(request);

    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/add")
    @ApiOperation("新增")
    @ModifyLog(serviceClass = AgentInfoService.class,modifyType = ModifyName.SAVE)
    public ResponseData add(@RequestBody AddAgentInfoReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return agentInfoService.add(req,loginInfoId);

    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/update")
    @ApiOperation("修改")
    @ModifyLog(serviceClass = AgentInfoService.class)
    public ResponseData update(@RequestBody UpdateAgentInfoReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return agentInfoService.update(req,loginInfoId);

    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/is_open")
    @ApiOperation("开启/关闭")
    @ModifyLog(serviceClass = AgentInfoService.class)
    public ResponseData open(@RequestBody UpdateOpenStatus req){
        Byte status = req.getStatus();
        Long id = req.getId();
        if (StringUtils.isEmpty(status) || StringUtils.isEmpty(id) || (status != -1 && status != 1)) {
            return ResponseData.fail(CodeIdEnum.IllegalParameter);
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return agentInfoService.open(id,status,loginInfoId);
    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/del")
    @ApiOperation("删除")
    @ModifyLog(serviceClass = AgentInfoService.class)
    public ResponseData del(@RequestBody DelReq req){
        if (StringUtils.isEmpty(req)) {
            return ResponseData.fail(CodeIdEnum.IllegalParameter);
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return agentInfoService.del(req.getId(),loginInfoId);
    }


    @Log
    @Token
    @GetMapping("/search")
    @ApiOperation("代理商下拉框查询")
    public ResponseData<List<AgentSearchResp>> search(String content){
        Long loginId = Long.parseLong(getAttribute());
        SysUserLoginInfo loginInfo = sysUserService.selectUserById(loginId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        Long areaId = null;
        if (loginInfo.getSysCompanyAreaId() != 0){
            areaId = loginInfo.getSysCompanyAreaId();
        }
        return agentInfoService.search(content,areaId);
    }

    @Log
    @Token
    @GetMapping("/search_open")
    @ApiOperation("代理商下拉框查询--(只查询开启状态代理商)")
    public ResponseData<List<AgentSearchResp>> searchOpen(String content){
        Long loginId = Long.parseLong(getAttribute());
        SysUserLoginInfo loginInfo = sysUserService.selectUserById(loginId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        Long areaId = null;
        if (loginInfo.getSysCompanyAreaId() != 0){
            areaId = loginInfo.getSysCompanyAreaId();
        }
        return agentInfoService.searchOpen(content,areaId);

    }

    @Log
    @Token
//    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/getAreaToAgent")
    @ApiOperation("商品已上架/未上架关联大区/代理商列表")
    public ResponseData<List<AreaAgentListResp>> getAreaToAgent(AreaAgentListReq request){
        //查询商品已绑定的代理商
        List<MallAgentCommodity> commodityList = mallCommodityService.findAgentCommomdityList(request.getCommodityId());

        //大区代理商
        List<AreaAgentListResp> areaList = agentInfoService.findAreaByAreaOrAgentId(request);
        List<AgentListResp> agentList = agentInfoService.findAgentByAreaOrAgentId(request);

        for (AgentListResp agent : agentList){
            for (MallAgentCommodity commodity : commodityList){
                if (commodity.getAgentId().equals(agent.getAgentId())){
                    agent.setType((byte) 1);//标记未上架过
                }
            }
        }
        Map<Long, List<AgentListResp>> collect = agentList.stream().collect(Collectors.groupingBy(AgentListResp::getAreaId));
        for (AreaAgentListResp area : areaList){
            List<AgentListResp> agentListResps = collect.get(area.getAreaId());
            area.setAgentListResps(agentListResps);
        }
        areaList.removeIf(resp -> CollectionUtils.isEmpty(resp.getAgentListResps()));

        return ResponseData.success(areaList);

    }

    @Log
    @GetMapping("/act_agent")
    @ApiOperation("活动关联代理商")
    public ResponseData<List<ActAreaAgentStoreResp>> actAgent(ActAreaAgentStoreReq req) {
        List<ActAgentResp> agentResps = agentInfoService.selectAgentList(req);

        Map<Long, List<ActAgentResp>> collect1 = agentResps.stream().collect(Collectors.groupingBy(ActAgentResp::getAreaId));
        List<ActAreaAgentStoreResp> result = agentInfoService.selectAreaList(req);
        for (ActAreaAgentStoreResp resp : result) {
            List<ActAgentResp> agentResps1 = collect1.get(resp.getId());
            resp.setChildren(agentResps1);
        }
        result.removeIf(area -> CollUtil.isEmpty(area.getChildren()));
        return ResponseData.success(result);
    }


}
